<template>
  <div class="login-container">
    <el-card class="login-card">
      <template #header>
        <div class="card-header">
          <h2>{{ isLogin ? '登录' : '注册' }}</h2>
        </div>
      </template>

      <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" type="password" placeholder="请输入密码"></el-input>
        </el-form-item>

        <template v-if="!isLogin">
          <el-form-item label="角色" prop="role">
            <el-select v-model="form.role" placeholder="请选择角色">
              <el-option label="学生" value="user"></el-option>
              <el-option label="教师" value="teacher"></el-option>
            </el-select>
          </el-form-item>

          <el-form-item v-if="form.role === 'user'" label="学号" prop="studentId">
            <el-input v-model="form.studentId" placeholder="请输入学号"></el-input>
          </el-form-item>
        </template>

        <el-form-item>
          <el-button type="primary" @click="handleSubmit">{{ isLogin ? '登录' : '注册' }}</el-button>
          <el-button @click="toggleMode">{{ isLogin ? '去注册' : '去登录' }}</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script>
import { ref, reactive } from 'vue';
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';

export default {
  name: 'Login',
  setup() {
    const router = useRouter();
    const formRef = ref(null);
    const isLogin = ref(true);

    const form = reactive({
      username: '',
      password: '',
      role: 'user',
      studentId: ''
    });

    const rules = {
      username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
      ],
      password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, message: '密码长度不能小于6个字符', trigger: 'blur' }
      ],
      role: [
        { required: true, message: '请选择角色', trigger: 'change' }
      ],
      studentId: [
        { required: true, message: '请输入学号', trigger: 'blur' }
      ]
    };

    const handleSubmit = async () => {
      if (!formRef.value) return;

      await formRef.value.validate(async (valid) => {
        if (valid) {
          try {
            const url = `${isLogin.value ? 'http://localhost:3000/api/auth/login' : 'http://localhost:3000/api/auth/register'}`;
            console.log(url);

            const response = await fetch(url, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json'
              },
              body: JSON.stringify(form)
            });

            const data = await response.json();

            if (response.ok) {
              // 保存token和用户信息
              localStorage.setItem('token', data.token);
              localStorage.setItem('user', JSON.stringify(data.user));

              ElMessage.success(isLogin.value ? '登录成功' : '注册成功');

              // 根据角色跳转到不同页面
              if (data.user.role === 'teacher') {
                router.push('/students');
              } else {
                router.push(`/student/${data.user.studentId}`);
              }
            } else {
              ElMessage.error(data.error || '操作失败');
            }
          } catch (error) {
            ElMessage.error('网络错误，请稍后重试');
          }
        }
      });
    };

    const toggleMode = () => {
      isLogin.value = !isLogin.value;
      form.username = '';
      form.password = '';
      form.role = 'user';
      form.studentId = '';
    };

    return {
      formRef,
      form,
      rules,
      isLogin,
      handleSubmit,
      toggleMode
    };
  }
};
</script>

<style scoped>
.login-container {
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background: linear-gradient(135deg, #f5f7fa 0%, #e4e7eb 100%);
}

.login-card {
  width: 400px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  text-align: center;
}

.card-header h2 {
  margin: 0;
  color: #303133;
}

.el-form {
  margin-top: 20px;
}

.el-button {
  margin-right: 10px;
}
</style>